package org.jerry.virtualoperator.controller;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.github.kevinsawicki.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.jerry.virtualoperator.constant.StringConstant;
import org.jerry.virtualoperator.form.VsmsTemplateCheckForm;
import org.jerry.virtualoperator.form.VsmsTmpV2CreateForm;
import org.jerry.virtualoperator.vo.Click;
import org.jerry.virtualoperator.vo.TemplateReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author JerryZeng
 * @date 2020/12/3
 */

@Slf4j
@RestController
@RequestMapping("api/v2/vsms/template")
public class VsmsTmpV2Controller {

  @Value("${server.tomcat.basedir}")
  private String baseDir;
  @Autowired
  Cache<Long, String> templateBackCache;

  @PostMapping
  public Click<Long> create(@RequestBody VsmsTmpV2CreateForm form) throws Exception{
    log.info("receive tmp create form, sign:{} and title:{}", form.getSign(), form.getTitle());
    long id = System.currentTimeMillis();
    File dir = new File(baseDir + File.separator + StringConstant.TEMPLATE_FILE_DIR);
    if(!dir.exists()) {
      dir.mkdir();
    }

    String curDirPath = baseDir + File.separator + StringConstant.TEMPLATE_FILE_DIR +
      File.separator + id + File.separator;
    Files.createDirectory(Paths.get(curDirPath));

    for (VsmsTmpV2CreateForm.FileCreateMeta meta : form.getMetas()) {
      Files.write(Paths.get(curDirPath + File.separator + meta.getName()), meta.getData(),
        StandardOpenOption.CREATE);
    }

    return Click.succ(id);
  }

  @PostMapping("check")
  public Click<?> check(@RequestBody VsmsTemplateCheckForm form) {
    log.info("check form: {}", JSONUtil.toJsonStr(form));
    TemplateReport report = new TemplateReport(form.getId(), form.getCarrier(), form.getStatus());

    String body = HttpRequest.post(form.getUrl())
        .trustAllCerts()
        .trustAllHosts()
        .connectTimeout(5000)
        .readTimeout(5000)
        .acceptJson()
        .contentType(MediaType.APPLICATION_JSON_VALUE)
        .send(JSONUtil.toJsonStr(report))
        .body();

    log.info("receive report body is {}", body);
    return Click.succ();
  }
}
